// src/request_auth.rs

use crate::auth;
use actix_web::{dev::Payload, error, Error, FromRequest, HttpRequest};
use std::future::{ready, Ready};
#[macro_export]
macro_rules! derive_from_request {
    ($struct_name:ident) => {
        impl FromRequest for $struct_name {
            type Error = Error;
            type Future = Ready<Result<Self, Self::Error>>;

            fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
                ready({
                    let auth = req.headers().get("Authorization");
                    if let Some(val) = auth {
                        let token = val
                            .to_str()
                            .unwrap()
                            .split("Bearer ")
                            .collect::<Vec<&str>>()
                            .pop()
                            .unwrap();
                        let result = auth::validate_token(token);
                        match result {
                            Ok(data) => Ok($struct_name { id: data.claims.id }),
                            Err(e) => {
                                eprintln!("Invalid Authorization {}", e);
                                Err(error::ErrorBadRequest("Invalid Authorization"))
                            }
                        }
                    } else {
                        eprintln!("Authorization Not Found");
                        Err(error::ErrorUnauthorized("Authorization Not Found"))
                    }
                })
            }
        }
    };
}
